import dayjs from "dayjs"
function funcInit() {
  //获取节点处
  let input = document.getElementById('message')
  let btn = document.getElementById('btn')
  let msgList = document.getElementById('msgList')

  //监听发送信息按钮
  btn.addEventListener('click', handleSendMsg, false)
  //创建websocket实例
  const ws = new WebSocket('ws://localhost:8000')

  //websocket得到连接时判断登录状态。
  ws.onopen = function (e) {
    if (!localStorage.getItem('username')) {
      location.href = '/entry.html'
      return
    }
  }

  //ws接受信息的处理时间
  ws.onmessage = function (e) {
    const res = JSON.parse(e.data)
    msgList.appendChild(createEle(res))
    input.value = ''
  }

  // 处理信息并发送
  function handleSendMsg() {
    const inputValue = input.value
    let sendMsg = {
      name: localStorage.getItem('username'),
      time: dayjs(new Date()).format("YYYY-MM-DD hh:mm:ss"),
      msg: inputValue,
    }
    if (!sendMsg) {
      alert('failed')
      return
    }
    ws.send(JSON.stringify(sendMsg))
  }

  

  //创建li节点的函数
  function createEle(data) {
    const { name, time, msg } = data
    const liEle = document.createElement('li')
    liEle.innerHTML = `
      <span>${name}</span><span>  ${time}</span>
      <p>${msg}</p>
    `
    return liEle
  }
  /* ws.onclose = function(e){
    console.log("连接关闭"+e)
  } */
  
}
funcInit()
